package com.shouyun.modules.oss.controller;

import com.alibaba.fastjson.JSONObject;
import com.shouyun.common.constant.Constant;
import com.shouyun.common.exception.ShouYunException;
import com.shouyun.common.utils.DataUtils;
import com.shouyun.common.utils.Result;
import com.shouyun.modules.oss.service.OssService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.net.URLDecoder;
import java.util.*;

/**
 * 文件上传
 *
 * @author Sunshouguo sunshouguo_java@163.com
 */
@RestController
@RequestMapping("api/oss")
public class ApiOssController {
    @Autowired
    private OssService ossService;

    /**
     * 查看分享
     *
     * @param sign
     * @param httpRequest
     * @return
     */
    @GetMapping("getInfo/{sign}")
    public Result getInfo(@PathVariable("sign") String sign, HttpServletRequest httpRequest) {
        if (StringUtils.isBlank(sign)) {
            return new Result().error("缺少参数");
        }
        JSONObject shareFile = DataUtils.getData(DataUtils.SHARE, sign);
        Date nowDate = new Date();
        if (shareFile != null && shareFile.size() > 0) {
            Integer shareExpireDay = shareFile.getInteger("expireDay");
            Date expireDate = shareFile.getDate("expireDate");
            if (shareExpireDay != -1 && expireDate.before(nowDate)) {
                shareFile = null;
                DataUtils.removeData(DataUtils.SHARE, sign);
            }
        }
        try {
            String path = shareFile.getString("path");
            if (StringUtils.isNotBlank(path)) {
                path = URLDecoder.decode(path, "utf-8");
                path = getWorkspaceAndPath(path);
            }
            File file = new File(path);
            shareFile.put("fileExists", file.exists());
        } catch (Exception e) {
            e.printStackTrace();
        }

        String token = getRequestToken(httpRequest);
        JSONObject user = null;
        if (StringUtils.isNotBlank(token)) {
            user = DataUtils.getData(DataUtils.TOKEN, token);
        }
        return new Result().ok(shareFile, user);
    }

    /**
     * 获取请求的token
     */
    private String getRequestToken(HttpServletRequest httpRequest) {
        //从header中获取token
        String token = httpRequest.getHeader(Constant.TOKEN_HEADER);

        //如果header中不存在token，则从参数中获取token
        if (StringUtils.isBlank(token)) {
            token = httpRequest.getParameter(Constant.TOKEN_HEADER);
        }

        return token;
    }

    /**
     * 下载文件
     *
     * @param sign
     * @param request
     * @param response
     * @throws Exception
     */
    @GetMapping("download")
    public void upload(String sign, HttpServletRequest request, HttpServletResponse response) throws Exception {
        JSONObject shareFile = DataUtils.getData(DataUtils.SHARE, sign);
        if (shareFile != null && shareFile.size() > 0) {
            Integer shareExpireDay = shareFile.getInteger("expireDay");
            Date expireDate = shareFile.getDate("expireDate");
            if (shareExpireDay != -1 && expireDate.before(new Date())) {
//                shareFile = null;
                DataUtils.removeData(DataUtils.SHARE, sign);
                return;
            }
        }
        String path = shareFile.getString("path");
        if (StringUtils.isBlank(path)) {
            return;
        }
        path = URLDecoder.decode(path, "utf-8");
        path = getWorkspaceAndPath(path);
        File file = new File(path);
        ossService.download(file, response);
    }

    /**
     * 获取路径
     *
     * @param path
     * @return
     */
    public String getWorkspaceAndPath(String path) {
        //获取参数
        JSONObject sysParams = DataUtils.getData(DataUtils.PARAMS, "sys");
        String workspace = sysParams.getString("workspace");
        if (StringUtils.isBlank(workspace)) {
            throw new ShouYunException("请先配置工作空间");
        }
        if (StringUtils.isNotBlank(path) && path.indexOf('\\') != -1) {
            workspace += path;
        }
        return workspace;
    }
}